/**
参考网址：https://blog.csdn.net/qq_43766999/article/details/120344401

OpenLayers实战（三）地图打点，自定义图标
*/
<template>
  <div>
    <div ref="map" id="map"></div>
    <div class="btns">
      <button @click="showStyle('circle')">显示样式circle</button>
      <button @click="showStyle('icon')">显示样式icon</button>

      <button @click="addMarkers">添加自定义图标</button> 
    </div>
  </div>
</template>

<script>
  import "ol/ol.css";
  import { Map, View, Feature } from "ol";
  import TileLayer from "ol/layer/Tile";
  import XYZ from "ol/source/XYZ";
  import VectorSource from "ol/source/Vector";
  import VectorLayer from "ol/layer/Vector";
  import { Style, Circle as CircleStyle, Fill, Stroke, Text, Icon } from "ol/style";
  import { Point } from "ol/geom";

  export default {
    name: "AppCustomStyle",
    data() {
      return {
        map: null,
        markerSource: null,
        markerLayer: null,
      };
    },
    mounted() {

      // 创建地图
      this.initMap();
      // ===== 创建数据源和图层并加入map的图层 =====
      this.markerSource = new VectorSource({ // 矢量数据源
        features: [],
      });
      this.markerLayer = new VectorLayer({ // 矢量图层
        style: null, // 设置style为null，后面可以通过改变样式控制marker的显示隐藏
        source: this.markerSource,
      });
      this.map.addLayer(this.markerLayer);

    },
    methods: {
      /**
      * 初始化一个 openlayers 地图
      */
      initMap() {
        this.map = new Map({
          target: "map",
          view: new View({
            center: [120.0, 30.0],
            zoom: 10,
            projection: "EPSG:4326",
          }),
        });
        var gaodeLayer = new TileLayer({
          source: new XYZ({
            url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
          })
        });
        this.map.addLayer(gaodeLayer);
      },


      addMarkers() {
        //业务数据
        let markers = [{
          id: '001',
          'coordinate': '120.0, 30.0',
          'featureName': 'marker1',
          'type': 'circle',
        }, {
          id: '002',
          'coordinate': '120.1, 30.1',
          'featureName': 'marker2',
          'type': 'icon',
        }, {
          id: '003',
          'coordinate': '120.2, 30.2',
          'featureName': 'marker3',
          'type': 'circle',
        }, {
          id: '004',
          'coordinate': '120.3, 30.3',
          'featureName': 'marker3',
          'type': 'circle',
        },];
        // 遍历markers并转换为features
        let features = markers.map(item => {
          if (item.coordinate) {
            let lonAndLat = item.coordinate.split(',');
            let feature = new Feature({
              geometry: new Point(lonAndLat),
              name: item.featureName || '',
              id: item.id,
              type: item.type,
            });


            let params = {
              // circle: { radius: 2, strokeColor: '#4499CC' },
              // icon: { url: require("@/assets/img/car.png"), opacity: 0.8 },
              text: { content: 'xxm', }
            };

            feature.setStyle(customStyle(item.type, params));
            feature.set('key', 'value');
            console.log('=====', feature);

            return feature;
          }
        });
        this.markerSource.addFeatures(features);

      },

      showStyle(styleType) {
        console.log('=================:', styleType)
        //  图层和vectorSource数据源，遍历source数据源，将符合条件的feature的style置空或者重新设置样式
        let features = this.markerSource.getFeatures();
        features.forEach(feature => {
          if (feature.get('type') === 'circle') {
            feature.setStyle(null); // 隐藏
          }
          if (feature&&feature.get('type') === 'icon') {
            let params = {
              icon: { url: require("@/assets/img/car.png") },
            };
            feature.setStyle(customStyle('icon', params)) // 重现
          }
        });

      },
    }
  };

  /**
* 封装一个方法快速返回自定义样式
* @param type 类型，目前只写了circle以及icon
* @param params 具体要自定义的属性
* @returns {ol.style.Style}
*/
  function customStyle(type, params = {}) {
    return new Style({
      image: getImageStyle(params),
      text: getTextStyle(params),
    });
    // 自定义图片
    function getImageStyle(params = {}) {
      let circle = params.circle || {};
      let icon = params.icon || {};
      switch (type.toLowerCase()) {
        case 'circle':
          return new CircleStyle({
            radius: circle.radius || 10,
            stroke: new Stroke({
              color: circle.strokeColor || '#FF0000'
            }),
            fill: new Fill({
              color: circle.fillColor || '#FF0000'
            })
          })
        case 'icon':
          return new Icon({
            src: icon.url || require("@/assets/img/icon_car.png"), // 路径
            offset: icon.offset || [0, 0], // 偏移，默认为 [0, 0]
            scale: icon.scale || 1, // 图标缩放比例，默认为 1
            opacity: icon.opacity || 1, // 透明度，默认为 1
          });
        default:
          return null;
      }
    }
    // 自定义文字
    function getTextStyle(params = {}) {
      let text = params.text || {};
      return new Text({
        text: text.content || '', // 文本内容
        font: text.font || 'normal 14px 微软雅黑', //文字样式
        fill: new Fill({
          color: text.fillColor || '#333'
        }), // 文字颜色
        stroke: new Stroke({
          color: text.strokeColor || '#ffcc33',
          width: text.strokeWidth || 2,
        }), // 文字描边
        textAlign: text.textAlign || 'center', // 文字对齐
        textBaseline: text.textBaseline || 'middle', //基准线
        offsetX: text.offset ? text.offset[0] : 0, // X轴偏移
        offsetY: text.offset ? text.offset[1] : 0, // Y轴偏移
      })
    }
  }

</script>

<style scoped> 
  #map {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }

  /*移除OSM的链接*/
  :deep(.ol-attribution) {
    display: none;
  }

  .btns {
    position: fixed;
    top: 100px;
    left: 200px;
  }
</style>